﻿/*****************************************介绍*****************************************
 * 作者：Ywh
 * 创建时间：2023-04-14　02:22:00
 * 功能：对象池管理器
**************************************************************************************/

using System.Collections.Generic;
using UnityEngine;

namespace Game.Framework
{
    [InternalModule(4)]
    public class PoolManager : BaseManager<PoolManager>, IModule
    {
        private Dictionary<string, ObjectPool> m_PoolDic;
        private GameObject m_PoolRoot;

        private PoolManager() { }

        public GameObject Get(string poolKey)
        {
            if (m_PoolDic == null) return null;
            if (m_PoolDic.TryGetValue(poolKey, out ObjectPool pool))
                return pool.Get();
            else
            {
                LogManager.LogError($"不存在的对象池，poolName:{poolKey}！！！", "PoolManager", "NoExist");
                return null;
            }
        }

        public void Delete(string poolKey, GameObject target)
        {
            if (m_PoolDic == null) return;
            if (m_PoolDic.TryGetValue(poolKey, out ObjectPool pool))
                pool.Delete(target);
            else
                LogManager.LogError($"不存在的对象池，poolName:{poolKey}！！！", "PoolManager", "NoExist");
        }

        public void CreatePool(string poolKey, GameObject item, int capacity)
        {
            if (m_PoolDic == null) return;
            if (!m_PoolDic.ContainsKey(poolKey))
            {
                m_PoolDic.Add(poolKey, new ObjectPool(poolKey, item, m_PoolRoot.transform, capacity));
            }
        }

        public void ClearPool(string poolKey)
        {
            if (m_PoolDic == null) return;
            if (m_PoolDic.TryGetValue(poolKey, out ObjectPool pool))
            {
                pool.Clear();
                m_PoolDic.Remove(poolKey);
            }
        }

        private InitResult m_InitResult;

        void IModule.Init()
        {
            m_InitResult = new InitResult(E_ResultType.Waiting);
            m_PoolDic = new Dictionary<string, ObjectPool>();
            m_PoolRoot = new GameObject("Pool");
            Object.DontDestroyOnLoad(m_PoolRoot);
            m_InitResult.type = E_ResultType.Success;
        }

        InitResult IModule.GetInitResult() => m_InitResult;

        void IModule.Clear()
        {
            foreach (var item in m_PoolDic.Values) item.Clear();
            m_PoolDic.Clear();
            m_PoolDic = null;
            if (m_PoolDic != null)
                Object.Destroy(m_PoolRoot);
            m_PoolRoot = null;
        }
    }
}
